import constant from './constant'
import util from './util'
var headers={
  'content-type': 'application/json;charset=UTF-8',
  "ProjectsId":constant.PROJECTS_ID,
  "App-Id":constant.APP_ID,
  "App-Key":constant.APP_KEY,
  "Sign":"MD5="
}

var network={
  get(url, params, message='加载中...',errorShow=true){
    dd.showLoading({
      content: message
    });
    return new Promise((resolve,reject)=>{
      dd.httpRequest({
        url: url+"?appId="+constant.APPID,
        data: params,
        headers:{
          ...headers,
          "Access-Token":util.getStorage(constant.TOKEN)
        },
        method: 'GET',
        dataType:'json',
        timeout:30000,
        success:  (res)=> {
          dd.hideLoading()
          this.dealResponse(res,resolve,reject)
        },
        fail: function (res) {
          dd.hideLoading()
          util.showToast(res.errMsg || '网络故障')
          reject(res)
        }
      })
    })
  },
  post(url, params, message='加载中...',errorShow=true){
    dd.showLoading({
      content: message
    });
    return new Promise((resolve,reject)=>{
      dd.httpRequest({
        url: url+"?appId="+constant.APPID,
        data: params,
        headers:{
          ...headers,
          "Access-Token":util.getStorage(constant.TOKEN)
        },
        method: 'POST',
        dataType:'json',
        timeout:30000,
        success:  (res)=> {
          dd.hideLoading()
          this.dealResponse(res,resolve,reject)
        },
        fail: function (res) {
          dd.hideLoading()
          util.showToast(res.errMsg || '网络故障')
          reject(res)
        }
      })
    })
  },
  dealResponse(res,resolve,reject){
    var {data,status}=res
    console.log(data,status)
    if (status == 200 && data.code == 200) {
      resolve(data.data)
    } else if (data.code == 502 || data.code == 506003) {
      util.showToast('令牌失效，重新登录')
      setTimeout(function(){
        util.removeStorage(constant.USER_INFO)
        util.removeStorage(constant.TOKEN)
        dd.navigateTo({
          url: '/pages/login/index'
        })
      },1000)
    } else {
      var msg=data.data == null ? data.message : typeof (data.data) == 'object' ? JSON.stringify(data.data) : data
      util.showToast(msg)
      reject(msg)
    }
  }
}

export default network